package j20251103;

public class Solution2 {
    boolean[][] vis;
    int m,n;
    int[] dx={0,0,1,-1};
    int[] dy={1,-1,0,0};
    public int[][] floodFill(int[][] image, int sr, int sc, int color) {
        if(image[sr][sc]==color){
            return image;
        }
        m=image.length;
        n=image[0].length;
        vis=new boolean[m][n];
        vis[sr][sc]=true;
        dfs(image,sr,sc,color);
        image[sr][sc]=color;
        return image;
    }
    public void dfs(int[][] image,int i,int j,int color){
        for(int k=0;k<4;k++){
            int x=i+dx[k];
            int y=j+dy[k];
            if(x>=0&&x<m&&y>=0&&y<n&&!vis[x][y]&&image[x][y]==image[i][j]){
                vis[x][y]=true;
                dfs(image,x,y,color);
                vis[x][y]=false;
                image[x][y]=color;
            }
        }
    }
}
